package com.ericsson.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ericsson.enap.modules.monitor.entity.EpcCron;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class TaskUtils {

    private static LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer;

    public static void invokMethod(EpcCron config) {
        Object obj = null;
        Class clazz = null;

        //通过Spring上下文去找 也有可能找不到
        try {
            obj = SpringUtils.getBean(config.getClassPath().split("\\.")[config.getClassPath().split("\\.").length - 1]);
            if (obj == null) {
                clazz = Class.forName(config.getClassPath());
                obj = clazz.newInstance();
            } else {
                clazz = obj.getClass();
            }
        } catch (Exception e) {
            throw new RuntimeException("ERROR:TaskUtils is Bean Create please check the classpath is`t right or not");
        }
        //方法执行
        try {
            //入参
            JSONObject jsonObject = null;
            String reqParms = config.getParameters();
            if (reqParms != null && reqParms.length() > 0) {
                jsonObject = JSON.parseObject(reqParms);
            }
            //获得方法名
            Method[] methods = clazz.getMethods();
            for (Method method1 : methods) {
                //不带参的
                if ((config.getMethodName().equals(method1.getName()) && jsonObject== null) ){
                    method1.invoke(obj);
                    return;
                }
                //带参的
                if ((config.getMethodName().equals(method1.getName()) && method1.getParameterCount()== jsonObject.size()) ){
                    Object[] params = new Object[method1.getParameterCount()];
                    if (localVariableTableParameterNameDiscoverer == null){
                        localVariableTableParameterNameDiscoverer= new LocalVariableTableParameterNameDiscoverer();
                    }
                    String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method1);
                    Parameter[] parameters = method1.getParameters();
                    for (int i = 0; i < parameterNames.length; i++) {
                        Class<?> type = parameters[i].getType();
                        Object object = jsonObject.getObject(parameterNames[i], type);
                        params[i]=object;
                    }
                    method1.invoke(obj,params);
                    return;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("ERROR:TaskUtils is Bean the method execute please check the methodName is`t right or not");
        }
    }
}
